import { Session } from './Session'

export class HttpClient {

    /**是否在请求中移除 projectId */
    removeProjectId = false

    fetch(url: RequestInfo, init: RequestInit | undefined): Promise<Response> {
        // if (typeof init != "undefined") {
        //     init.headers = this.getHeaders()
        // }
        return window.fetch(url, init)
    }

    /**
     * 执行 HTTP GET 请求
     * @param url API 地址
     * @param contentType 
     */
    get(url: string, contentType: string = "application/json"): Promise<Response> {
        return this.fetch(url, {
            method: "get",
            headers: this.getHeaders(contentType)
        })
    }

    private getHeaders(contentType: string = "application/json") {
        const user = Session.getUser()
        const token = Session.getApiToken()
        const data = {
            "Authorization": token,
            "token": token,
            "Content-Type": contentType
        }
        if (!this.removeProjectId) {
            (data as any)._TenantId = user?._TenantId ?? "";
            (data as any)._LoginProjectId = user?._LoginProjectId ?? "";
        }
        return data
    }

    /**生成一个适用于 WEB 平台的 HTTP 客户端 */
    static instance() {
        return new HttpClient()
    }

}